Spinner有兩種型態,第一種是下拉式(dropdown)、第二種是對話式(dialog)
可以在android:spinnerMode=" ",選擇想要的模式
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="100dp"
android:spinnerMode="dialog"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
程式碼:(裡面有詳細註解)
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//綁定元件
Spinner spinner = findViewById(R.id.spinner);
//建立選項文字
final String[] str = {"第0", "第1", "第2", "第3", "第4", "第5"};
ArrayAdapter<String> strList = new ArrayAdapter(MainActivity.this, //對應的Context
android.R.layout.simple_spinner_dropdown_item, //未展開時樣式
str); //上方剛設定的String[]資料
spinner.setAdapter(strList); //指定給要操作spinner
//展開時樣式,可不設置
strList.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
spinner.setSelection(3); //顯示一開始要出現的選項,若不設置預設為0
//spinner點擊監聽
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
// 選項有選取時的動作
Toast.makeText(MainActivity.this, "您選擇了:" + spinner.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
//getSelectedItem()是所選擇的選項內容
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
// 沒有選取時的動作
}
});
}
}
執行畫面:
選項內容: